package com.my.study.pool;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author Carlos
 * @version 1.0
 * @Description 定时任务/线程异常处理
 * @date 2021/6/13 22:51
 **/
@Slf4j(topic = "c.TestTimer")
public class TestTimer {

    public static void main(String[] args) {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);

        method1(pool);


//        log.debug("start...");
//        method2(pool);
//        method3(pool);

    }

    /**
     *scheduleWithFixedDelay()
     * 假设任务执行时间花费T1：
     *
     * 每次任务间隔时间为：T1 + delay
     *
     * @param pool
     */
    private static void method3(ScheduledExecutorService pool) {
        pool.scheduleWithFixedDelay(() -> {
            log.debug("running");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, 1, 1, TimeUnit.SECONDS);
    }

    /**
     * scheduleAtFixedRate()方法
     * 假设任务执行时间花费T1：
     *
     * 每次任务间隔时间为：Math.max(T1,period)
     *
     *
     * @param pool
     */
    private static void method2(ScheduledExecutorService pool) {
        pool.scheduleAtFixedRate(() -> {
            log.debug("running");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, 1, 2, TimeUnit.SECONDS);
    }


    private static void method1(ScheduledExecutorService pool) {
        pool.schedule(() -> {
            log.debug("task1");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, 1, TimeUnit.SECONDS);

        pool.schedule(() -> {
            log.debug("task2");
        }, 1, TimeUnit.SECONDS);
    }


}
